package com.corecloud.controller.sms;

import com.corecloud.entity.SysLogEntity;
import com.corecloud.mapper.mysql.SysLogMapper;
import com.corecloud.service.sms.ValidateCodeProcessor;
import com.corecloud.tools.LogEntryUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.annotation.Resources;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

@Component
public class SmsCodeFilter extends OncePerRequestFilter implements InitializingBean {

    @Autowired
    private AuthenticationFailureHandler authenticationFailureHandler;
    @Autowired
    private LogEntryUtils logEntryUtils;

    private Set<String> urls = new HashSet<>();

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public void afterPropertiesSet() throws ServletException {
        super.afterPropertiesSet();
        // 这里配置需要拦截的地址 ......
        urls.add("/oauthplatform/authentication/mobile");
    }

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                                    FilterChain filterChain) throws ServletException, IOException {
        boolean action = false;
        for (String url : urls) {
            String requestURI = httpServletRequest.getRequestURI();
            if (antPathMatcher.match(url, requestURI)) { action = true; break; }
        }
        if (action) {
            try {
                validate(httpServletRequest);
            } catch (SmsCodeException e) {
                authenticationFailureHandler.onAuthenticationFailure(httpServletRequest, httpServletResponse, e);
                return;
            }
        }
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }

    /**
     * 查验验证码是否有误
     * @param request
     */
    public void validate(HttpServletRequest request) {
//        手机号
        String mobile = request.getParameter("mobile");
//        Session中的验证码
        SmsCode smsCode = (SmsCode)request.getSession().getAttribute(ValidateCodeProcessor.SESSION_KEY_PREFIX + mobile);
//        用户输入的验证码
        String smsCodeRequest = request.getParameter("smsCode");
        if (smsCodeRequest == null || smsCodeRequest.isEmpty()) {
            String logText = "短信验证码不能为空";
            logEntryUtils.sysLogS(logText, mobile);
            throw new SmsCodeException(logText);
        }
        if (smsCode == null) {
            String logText = "短信验证码不存在";
            logEntryUtils.sysLogS(logText, mobile);
            throw new SmsCodeException(logText);
        }
        if (smsCode.isExpired()) {
            String logText = "短信验证码已过期";
            logEntryUtils.sysLogS(logText, mobile);
            request.getSession().removeAttribute(ValidateCodeProcessor.SESSION_KEY_PREFIX + smsCode);
            throw new SmsCodeException(logText);
        }
        if(!smsCodeRequest.equalsIgnoreCase(smsCode.getCode())) {
            String logText = "短信验证码错误";
            logEntryUtils.sysLogS(logText, mobile);
            throw new SmsCodeException(logText);
        }
        if(!smsCode.getMobile().equals(mobile)) {
            String logText = "输入的手机号与发送短信验证码的手机号不一致";
            logEntryUtils.sysLogS(logText, smsCodeRequest);
            throw new SmsCodeException(logText);
        }
    }


}
